//
//  AddMoneyViewController.m
//  PeopleStreet
//
//  Created by 刘建峰 on 16/6/6.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "AddMoneyViewController.h"
#import "PayViewController.h"
#import "AddmoneyTableViewCell.h"

static NSString * cellIndentifier = @"cellOne";

@interface AddMoneyViewController ()
<UITableViewDataSource,UITableViewDelegate> {
    NSString *topup;
    NSInteger number;
}
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UITableView *tableviewOne;
@property (weak, nonatomic) IBOutlet UIScrollView *scroView;;
@property (strong, nonatomic) IBOutlet UILabel *hightLabel;
@property (strong, nonatomic) IBOutlet UILabel *detailLable;
@property(nonatomic,strong)NSArray * addMoneyListArray;
@property(nonatomic,strong)NSMutableDictionary * addMoneyDicOne;
@property(nonatomic,strong)NSMutableDictionary * addMoneyDicTwo;
@property(nonatomic,strong)NSMutableDictionary * addMoneyDicThree;
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSArray * tableViewArray;
@property(nonatomic,strong)NSArray * buttonThreeArray;

@property (strong, nonatomic) IBOutlet UIButton *confirmationOne;
@property (strong, nonatomic) IBOutlet UIButton *confirmationTwo;

@property (strong, nonatomic) IBOutlet UIButton *buttonOne;
@property (strong, nonatomic) IBOutlet UIButton *buttonTwo;
@property (strong, nonatomic) IBOutlet UIButton *buttonThree;
@property (strong, nonatomic) IBOutlet UIButton *buttonFour;

@property (strong, nonatomic) IBOutlet UIView *viewOne;
@property (strong, nonatomic) IBOutlet UIView *viewTwo;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;

@property (strong, nonatomic) IBOutlet UIView *viewThree;
@property (strong, nonatomic) IBOutlet UILabel *sliderLabel;

@property (strong, nonatomic) IBOutlet UIButton *BGbutton;
@property (strong, nonatomic) IBOutlet UIView *payView;
@property (strong, nonatomic) IBOutlet UITextField *payField;
@property (strong, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic) IBOutlet UIButton *rightButton;
@property (strong, nonatomic) IBOutlet UITextField *topupAmountField;

@property (strong, nonatomic) IBOutlet UILabel *goldLabel;
@property (strong, nonatomic) IBOutlet UILabel *silverLable;

@end

@implementation AddMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _addMoneyDicOne = [NSMutableDictionary dictionary];
    _addMoneyDicTwo = [NSMutableDictionary dictionary];
    _addMoneyDicThree = [NSMutableDictionary dictionary];
    _array = [NSArray array];
    _tableViewArray = [NSArray array];
    _buttonThreeArray = [NSArray array];
    
    [self initViewLayout];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.viewOne];
    [self adaptiveViewLayout:self.viewTwo];
    [self adaptiveViewLayout:self.viewThree];
    [self adaptiveViewLayout:self.payView];
    
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
    
    _confirmationOne.layer.cornerRadius = 20*VerticalRatio();
    _confirmationTwo.layer.cornerRadius = 20*VerticalRatio();
    _viewOne.hidden = NO;
    _viewTwo.hidden = YES;
    _buttonOne.selected = YES;
    _buttonTwo.selected = NO;
    _buttonThree.selected = NO;
    _buttonFour.selected = NO;
    _sliderLabel.frame = flexibleFrame(CGRectMake(0, 41, 80, 1), NO);
    
    _payView.layer.cornerRadius = 5*VerticalRatio();
    _leftButton.layer.masksToBounds = YES;
    _leftButton.layer.cornerRadius = 20*VerticalRatio();
    _rightButton.layer.masksToBounds = YES;
    _rightButton.layer.cornerRadius = 20*VerticalRatio();
    
    [self.payField setValue:[UIColor colorWithWhite:0.604 alpha:1.000]
                 forKeyPath:@"_placeholderLabel.textColor"];
    self.payField .leftView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 15, 1), NO)];

}



- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}


#pragma mark === 充值类型
- (IBAction)type:(UIButton *)sender {
    _viewOne.hidden = YES;
    _viewTwo.hidden = YES;
    _buttonOne.selected = NO;
    _buttonTwo.selected = NO;
    _buttonThree.selected = NO;
    _buttonFour.selected = NO;
    _goldLabel.text = @"0";
    _silverLable.text = @"0";
    
    if (sender == _buttonOne) {
        [UIView animateWithDuration:0.2 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(0, 41, 80, 1), NO);
        }];
        _buttonOne.selected = YES;
        _viewOne.hidden = NO;
        _scroView.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
        
    } else if (sender == _buttonTwo) {
        [UIView animateWithDuration:0.2 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(80, 41, 80, 1), NO);
        }];
        _buttonTwo.selected = YES;
        _viewTwo.hidden = NO;
        _detailLable.text = @"充值说明：活动到期后曾送银币将清零。";
        [self getAddMoneyList];
        _tableView.hidden = NO;
        _tableviewOne.hidden = YES;
        [self countAddMoney];
        
    } else if (sender == _buttonThree) {
        [UIView animateWithDuration:0.2 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(160, 41, 80, 1), NO);
        }];
        _buttonThree.selected = YES;
        _viewTwo.hidden = NO;
        _detailLable.text = @"停车充值：该金额只能用于停车相关消费。";
        [self getAddMoneyList];
        _tableView.hidden = YES;
        _tableviewOne.hidden = NO;
        [self countAddMoney];
        
    } else if (sender == _buttonFour) {
        [UIView animateWithDuration:0.2 animations:^{
            _sliderLabel.frame = flexibleFrame(CGRectMake(240, 41, 80, 1), NO);
        }];
        _buttonFour.selected = YES;
        _viewTwo.hidden = NO;
        _detailLable.text = @"充值说明：提前充值，冻结期后才能使用。";
        [self getAddMoneyList];
        _tableView.hidden = NO;
        _tableviewOne.hidden = YES;
        [self countAddMoney];
    }
}

#pragma mark - 隐藏支付界面
- (IBAction)hidden:(id)sender {
    _BGbutton.hidden = YES;
    _payView.hidden = YES;
    _payField.text = @"";
}
#pragma mark - 确认支付
- (IBAction)pay:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    if (_buttonOne.selected) {
        
    } else if (_buttonTwo.selected) {
        
    } else if (_buttonThree.selected) {
        
    } else if (_buttonFour.selected) {
        
    }
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:_topupAmountField.text forKey:@"mepuEpurse"];
    [self.shareApi  requestOperationWithDic:dic withPath:SX_depositMemberEpurse withHttpType:@"POST" withTag:SX_SX_depositMemberEpurse];
    
}

#pragma mark - 确认
- (IBAction)button:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    if (_buttonOne.selected) {
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        if (_topupAmountField.text.length == 0) {
             [[CWHUDTips sharedInstance]  showTips:@"请输入充值金额"  withStatus:1 dismissAfter:1.5];
            return;
        }
        [dic setObject:_topupAmountField.text forKey:@"mepuEpurse"];
        [self.shareApi  requestOperationWithDic:dic withPath:SX_depositMemberEpurse withHttpType:@"POST" withTag:SX_SX_depositMemberEpurse];
    } else {
        NSDictionary *DIC;
        NSArray *array;
        NSString *type;
        if (_buttonTwo.selected) {
            DIC = _addMoneyDicOne;
            array = _tableViewArray;
            type = @"1";
        } else if (_buttonThree.selected) {
            DIC = _addMoneyDicTwo;
            array = _buttonThreeArray;
            type = @"2";
        } else if (_buttonFour.selected ) {
            DIC = _addMoneyDicThree;
            array = _tableViewArray;
            type = @"3";
        }
        if (DIC.allValues.count==0) {
            [[CWHUDTips sharedInstance]  showTips:@"请选择充值金额"];
            return;
        }
        
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        NSString * ids = @"";
        NSString * nums = @"";
        for (int i = 0;i<DIC.allKeys.count;i++ ) {
            NSString * rows = DIC.allKeys[i];
            NSInteger row = [rows integerValue];
            NSString * num = [NSString stringWithFormat:@",%@",DIC[rows]];
            
            NSString * addId = [NSString stringWithFormat:@",%@",array[row][@"mepuId"]];
            if (i == 0) {
                addId = [NSString stringWithFormat:@"%@",array[row][@"mepuId"]];
                num = [NSString stringWithFormat:@"%@",DIC[rows]];
            }
            ids = [ids stringByAppendingString:addId];
            
            nums = [nums stringByAppendingString:num];
        }
        
        [dic setObject:ids forKey:@"mepuId"];
        [dic setObject:nums forKey:@"num"];
        [dic setObject:type forKey:@"type"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_saveMemberEpurseOrder withHttpType:@"POST" withTag:SX_SX_saveMemberEpurseOrder];
        
    }
}


#pragma mark === 查询充值有礼列表
- (void)getAddMoneyList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    if (_buttonTwo.selected) {
        [dic setObject:@"1" forKey:@"type"];
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallEpurseList withHttpType:@"POST" withTag:SX_SX_queryMallEpurseList];
    } else if (_buttonThree.selected) {
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallEpurseParkList withHttpType:@"POST" withTag:SX_SX_queryMallEpurseParkList];
    }else if (_buttonFour.selected) {
        [dic setObject:@"3" forKey:@"type"];
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallEpurseList withHttpType:@"POST" withTag:SX_SX_queryMallEpurseList];
    } 
    
}


#pragma mark   === 确认充值生成充值订单
- (IBAction)sureAddMoney:(id)sender {
    
//    if (_addMoneyDic.allValues.count==0) {
//        [[CWHUDTips sharedInstance]  showTips:@"请选择充值金额"];
//        return;
//    }
//   
//    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
//    NSString * ids = @"";
//    NSString * nums = @"";
//    for (int i = 0;i<_addMoneyDic.allKeys.count;i++ ) {
//        NSString * rows = _addMoneyDic.allKeys[i];
//        NSInteger row = [rows integerValue];
//        NSString * num = [NSString stringWithFormat:@",%@",_addMoneyDic[rows]];
//        NSString * addId = [NSString stringWithFormat:@",%@",_addMoneyListArray[row][@"mepuId"]];
//        if (i == 0) {
//            addId = [NSString stringWithFormat:@"%@",_addMoneyListArray[row][@"mepuId"]];
//            num = [NSString stringWithFormat:@"%@",_addMoneyDic[rows]];
//        }
//        ids = [ids stringByAppendingString:addId];
//        
//        nums = [nums stringByAppendingString:num];
//    }
//    
//    [dic setObject:ids forKey:@"mepuId"];
//     [dic setObject:nums forKey:@"num"];
//    self.shareApi.delegate=self;
//    [self.shareApi  requestOperationWithDic:dic withPath:SX_saveMemberEpurseOrder withHttpType:@"POST" withTag:SX_SX_saveMemberEpurseOrder];
////
////    
}

//计算充值赠送金额
- (void)countAddMoney{
    NSDictionary *dic;
    if (_buttonTwo.selected) {
        dic = _addMoneyDicOne;
    } else if (_buttonThree.selected) {
        dic = _addMoneyDicTwo;
    } else if (_buttonFour.selected ) {
        dic = _addMoneyDicThree;
    }
    if (dic.allValues.count==0) {
//        _tureAddLabel.text = @"未选择充值金额";
        _goldLabel.text = @"0";
        _silverLable.text = @"0";
    }else{
        NSInteger addMoney = 0;
        NSInteger prsentMoney = 0;
        for (NSString * rows in dic.allKeys) {
            NSInteger num = [dic[rows]integerValue];
            NSInteger row = [rows integerValue];
            NSInteger add;
            NSInteger present;
            if (_buttonThree.selected) {
                add = [_buttonThreeArray[row][@"mepuRealMoney"] integerValue] * num;
                present = [_buttonThreeArray[row][@"mepuLabelMoney"] integerValue] * num;
            } else if (_buttonTwo.selected || _buttonFour.selected) {
                add = [_tableViewArray[row][@"mepuRealMoney"] integerValue] * num;
                present = [_tableViewArray[row][@"mepuLabelMoney"] integerValue] * num;
            }
            
            addMoney +=add;
            prsentMoney +=present;
        }

        _goldLabel.text = [NSString stringWithFormat:@"%d",addMoney];
        _silverLable.text = [NSString stringWithFormat:@"%d",prsentMoney];
    }
    
    
  
    
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        if (_buttonThree.selected) {
            return _buttonThreeArray.count;
        } else{
            return _tableViewArray.count+1;
        }
    } else {
        return _buttonThreeArray.count;
    }
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        if (_buttonTwo.selected) {
            if (indexPath.row == _tableViewArray.count) {
                cellIndentifier = @"cellTwo";
            }
            else {
                cellIndentifier = @"cellOne";
            }

        } else if (_buttonFour.selected) {
            if (indexPath.row == _tableViewArray.count) {
                cellIndentifier = @"cellTwo";
            }
            else {
                cellIndentifier = @"cellThree";
            }

        }
        
    } else {
        cellIndentifier = @"cell";
    }
    
    
    AddmoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    if (tableView == self.tableView) {
        if (indexPath.row == _tableViewArray.count) {
            NSString *begin = [NSString stringWithFormat:@"%@",_array[0][@"meacBeginTime"]];
            NSString *end = [NSString stringWithFormat:@"%@",_array[0][@"meacDueTime"]];
            
            long long beginTime=[begin longLongValue];
            NSDate *beginDate = [[NSDate alloc]initWithTimeIntervalSince1970:beginTime/1000.0];
            NSDateFormatter *formatterBegin = [[NSDateFormatter alloc]init];
            [formatterBegin setDateFormat:@"yyyy.MM.dd"];
            begin = [formatterBegin stringFromDate:beginDate];
            
            long long endTime=[end longLongValue];
            NSDate *endDate = [[NSDate alloc]initWithTimeIntervalSince1970:endTime/1000.0];
            NSDateFormatter *formatterEnd = [[NSDateFormatter alloc]init];
            [formatterEnd setDateFormat:@"yyyy.MM.dd"];
            end = [formatterEnd stringFromDate:endDate];
            
            [cell.time setTitle: [NSString stringWithFormat:@" 活动时间：%@ - %@",begin,end] forState:UIControlStateNormal];
        } else {
            
            cell.addMoneyLabel.text = [NSString stringWithFormat:@"充值%@送%@",_tableViewArray[indexPath.row][@"mepuRealMoney"],_tableViewArray[indexPath.row][@"mepuLabelMoney"]];
            cell.changeNumBlock = ^(NSInteger num){
                if (_buttonTwo.selected) {
                    if (num>=1) {
                        [_addMoneyDicOne setObject:@(num) forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
                    }else{
                        if ([_addMoneyDicOne.allKeys containsObject:[NSString stringWithFormat:@"%d",indexPath.row]]) {
                            [_addMoneyDicOne removeObjectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
                        }
                    }
                } else if (_buttonFour.selected) {
                    if (num>=1) {
                        [_addMoneyDicThree setObject:@(num) forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
                    }else{
                        if ([_addMoneyDicThree.allKeys containsObject:[NSString stringWithFormat:@"%d",indexPath.row]]) {
                            [_addMoneyDicThree removeObjectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
                        }
                    }
                }
                
                [self countAddMoney];
            };
        }
    } else {
        cell.addMoneyLabel.text = [NSString stringWithFormat:@"充值%@送%@",_buttonThreeArray[indexPath.row][@"mepuRealMoney"],_buttonThreeArray[indexPath.row][@"mepuLabelMoney"]];
        cell.changeNumBlock = ^(NSInteger num){
            if (num>=1) {
                [_addMoneyDicTwo setObject:@(num) forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
            }else{
                if ([_addMoneyDicTwo.allKeys containsObject:[NSString stringWithFormat:@"%d",indexPath.row]]) {
                    [_addMoneyDicTwo removeObjectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];

                }
            }
            [self countAddMoney];
        };
    }

    
    return cell;
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    if (tag == SX_SX_saveMemberEpurseOrder){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            PayViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Pay"];
            page.payOrderName = @"钱包充值";
            page.payOrderPrice = [NSString stringWithFormat:@"%@",database[@"result"][@"meorRealMoney"]];
            page.type = 3;
            page.payId = [NSString stringWithFormat:@"%@",database[@"result"][@"meorNo"]];
            
            [self.navigationController  pushViewController:page animated:YES];
        }
    }else if (tag == SX_SX_depositMemberEpurse){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary *dic = database[@"result"];
            topup = [NSString stringWithFormat:@"%@",dic[@"meorNo"]];
            _BGbutton.hidden = NO;
            _payView.hidden = NO;
        }
    } else if (tag == SX_SX_queryMallEpurseList){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _array = database[@"result"];
            _tableViewArray = database[@"result"][0][@"mallEpurse"];
            self.nameLabel.text = [NSString stringWithFormat:@"%@",_array[0][@"meacName"]];
            _hightLabel.frame = flexibleFrame(CGRectMake(10, 15, 2, (_tableViewArray.count+2)*50), NO);
            
            _tableView.frame = flexibleFrame(CGRectMake(10, 63, 300, 50*(_tableViewArray.count+1)), NO);
            _viewThree.frame = flexibleFrame(CGRectMake(0, (_tableView.frame.origin.y+_tableView.frame.size.height+20)/VerticalRatio(), 320, 128), NO);
            CGFloat hight = (_viewThree.frame.origin.y+_viewThree.frame.size.height+20)/VerticalRatio();
            if (hight <= 504) {
                hight = 505;
            }
            _scroView.contentSize = flexibleSize(CGSizeMake(0, hight), NO);
            _hightLabel.hidden = NO;
            _nameLabel.hidden = NO;
            _tableView.dataSource = self;
            _tableView.delegate = self;
            [_tableView reloadData];
           
        }
    } else if (tag == SX_SX_queryMallEpurseParkList){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _buttonThreeArray = database[@"result"];
            _hightLabel.hidden = YES;
            _nameLabel.hidden = YES;
            _tableviewOne.frame = flexibleFrame(CGRectMake(0, 15, 320, 50*_buttonThreeArray.count), NO);
            _viewThree.frame = flexibleFrame(CGRectMake(0, (_tableviewOne.frame.origin.y+_tableviewOne.frame.size.height+20)/VerticalRatio(), 320, 128), NO);
            CGFloat hight = (_viewThree.frame.origin.y+_viewThree.frame.size.height+20)/VerticalRatio();
            if (hight <= 504) {
                hight = 505;
            }
            _scroView.contentSize = flexibleSize(CGSizeMake(0, hight), NO);
            _tableviewOne.dataSource = self;
            _tableviewOne.delegate = self;
            [_tableviewOne reloadData];
            
        }
    }
    
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
